package org.ns.summer.data.jta;

import com.atomikos.icatch.jta.UserTransactionImp;
import com.atomikos.jdbc.AtomikosDataSourceBean;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import javax.transaction.*;

/**
 * 直接使用 AtomikosDataSourceBean 源
 */
public class JtaTransaction {
    Logger log = LoggerFactory.getLogger(getClass());
    private UserTransaction transaction = new UserTransactionImp();
    private boolean begin;
    public boolean isJta(DataSource dataSource) {
        return dataSource instanceof AtomikosDataSourceBean;
    }
    public boolean isJta(SqlSession sqlSession) {
        return sqlSession.getConfiguration().getEnvironment().getDataSource() instanceof AtomikosDataSourceBean;
    }

    public void begin() throws NotSupportedException, SystemException {
        if (! begin) {
            transaction.begin();
            begin = true;
        }
    }

    public void commit() throws RollbackException,
            HeuristicMixedException, HeuristicRollbackException, SecurityException,
            IllegalStateException, SystemException {
        begin = false;
        transaction.commit();
    }

    public void rollback() throws IllegalStateException, SecurityException,
            SystemException {
        begin = false;
        transaction.rollback();

    }
    public void rollbackNoThrows() {
        try {
            rollback();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setRollbackOnly() throws IllegalStateException, SystemException {
        transaction.setRollbackOnly();
    }


    public int getStatus() throws SystemException {
        return transaction.getStatus();
    }


    public void setTransactionTimeout(int seconds) throws SystemException {
        transaction.setTransactionTimeout(seconds);
    }

    public boolean isBegin() {
        return begin;
    }
}
